package com.taoist_awei.blog.exception;

import com.taoist_awei.blog.core.HttpResult;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author 高威
 * 接口异常统一处理
 *
 */
@RestControllerAdvice
public class CustomizeExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler({ApiException.class})
    public ResponseEntity<?> handleInvalidResponse(RuntimeException e, WebRequest request) {
        ApiException apiException = (ApiException) e;
        HttpResult result = apiException.getResult();
        HttpHeaders headers = new HttpHeaders();
        HttpStatus status = HttpStatus.ACCEPTED;
        headers.setContentType(MediaType.APPLICATION_JSON);
        return handleExceptionInternal(e, result, headers, status, request);
    }

    @ExceptionHandler({ValidationException.class})
    public ResponseEntity<?> handleValidationResponse(ValidationException e, WebRequest request) {
        ConstraintViolationException exception = (ConstraintViolationException) e;
        Set<ConstraintViolation<?>> constraintViolations = exception.getConstraintViolations();
        List<String> message = new ArrayList<>();
        for (ConstraintViolation<?> item : constraintViolations) {
            message.add(item.getMessage());
        }
        HttpResult result = new HttpResult.HttpResultBuilder()
                .message("参数错误")
                .statusCode(400)
                .data(message)
                .build();
        HttpHeaders headers = new HttpHeaders();
        HttpStatus status = HttpStatus.ACCEPTED;
        headers.setContentType(MediaType.APPLICATION_JSON);
        return handleExceptionInternal(e, result, headers, status, request);
    }
}
